package org.bouscarlo.jj2000.decoding.service;

import java.io.ByteArrayInputStream;

import jj2000.j2k.image.BlkImgDataSrc;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class JJ2000DecodingServiceImpl extends Service {
	private static final String JJ2000_DECODING_ACTION_SERVICE = "bouscarlo.intent.action.jj2000.DecodingService";
	private final static String LOG_TAG = JJ2000DecodingServiceImpl.class.getCanonicalName();

	private Handler handler=null;
	
	@Override
	public void onCreate() {
		super.onCreate();
		handler=new Handler();
		toast("Creating Service");
		Log.d(LOG_TAG,"The JJ2000DecoderService was created.");
	}

	@Override
	public void onDestroy() {
		Log.d(LOG_TAG,"The JJ2000DecoderService was destroyed.");
		toast("Closing Service");
		super.onDestroy();
	}


	@Override
	public IBinder onBind(Intent intent) {
		toast("Binding Service");
		if(JJ2000_DECODING_ACTION_SERVICE.equals(intent.getAction())) {
			Log.d(LOG_TAG,"The JJ2000DecoderService was binded.");
			return new JJ2000DecodingServiceStub(this);
		}
		return null;
	}

	JJ2000Bitmap decodeImage(byte[] jp2) throws Exception  {
		try {
			toast("Decoding Image...");
			JJ2000Decoder decoder=new JJ2000Decoder();
			BlkImgDataSrc img=decoder.decodeJP2(new ByteArrayInputStream(jp2));
			return decoder.encodeBMP(img);
		} catch (Exception e){
			toast("Error generating Image: "+e.getMessage());
		}
		return null;
	}
	
	public void toast(final String message) {
		handler.post(new Runnable() {
			public void run() {
				Toast.makeText(getApplicationContext(), "JJ2000DecodingService: "+message, Toast.LENGTH_SHORT).show();
			}
		});
	}


}
